package svc

import (
	"log"
	"os"
	"time"

	"gitee.com/liuxuezhan/ar-platform/base-common/rpc/interceptors"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/setting/client/settingtoc"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userservice"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/config"
	"gitee.com/liuxuezhan/ar-platform/base-common/rpc"
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/zrpc"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

type ServiceContext struct {
	Config     config.Config
	Db         *gorm.DB
	SettingRpc settingtoc.SettingToC
	UserRpc    userservice.UserService
}

func NewServiceContext(c config.Config) *ServiceContext {
	settingRpc, err := zrpc.NewClient(zrpc.RpcClientConf{
		Target: rpc.GenRpcTarget(c.SettingRpc),
	}, zrpc.WithUnaryClientInterceptor(interceptors.ClientErrorInterceptor(c.Name, c.Name)))
	if err != nil {
		logx.Error(err)
	}

	userRpc, err := zrpc.NewClient(zrpc.RpcClientConf{
		Target: rpc.GenRpcTarget(c.UserRpc),
	}, zrpc.WithUnaryClientInterceptor(interceptors.ClientErrorInterceptor(c.Name, c.Name)))
	if err != nil {
		logx.Error(err)
	}

	return &ServiceContext{
		Config:     c,
		Db:         DbConnect(c),
		SettingRpc: settingtoc.NewSettingToC(settingRpc),
		UserRpc:    userservice.NewUserService(userRpc),
	}
}

var Db *gorm.DB

func DbConnect(conf config.Config) *gorm.DB {
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             time.Second, // Slow SQL threshold
			LogLevel:                  logger.Info, // Log level
			IgnoreRecordNotFoundError: false,       // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      false,       // Don't include params in the SQL log
			Colorful:                  true,        // Disable color
		},
	)
	Db, _ = gorm.Open(mysql.Open(conf.DataSource), &gorm.Config{Logger: newLogger})

	sqlDB, _ := Db.DB()
	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)

	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)

	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)

	return Db
}
